"""
Frame for file input.
"""

import os
import tkinter as tk
import tkinter.filedialog as fd
from ui.DataProvidingFrame import DataProvidingFrame
from ui.ByteGenToBitGen import byteGeneratorToBit

class CrcFileChoiceFrame(DataProvidingFrame):

    def get_help_message(self):
        return """You can select a file with any extension you want.
When this is done, the name of the file
is displayed next to the button."""

    def getDataGenerator(self):
        """Override from DataProvidingFrame.
        Return a generator (or None) for the data."""
        if not self.filename:
            return None

        def gen():
            self.file = open(self.filename, 'rb')
            try:
                for i in self.file.read():
                    yield i
            finally:
                self.file.close()
        g = gen()
        g = byteGeneratorToBit(g)()
        return g

    def getDataSize(self):
        """Override from DataProvidingFrame.
        Return the size of the data."""
        return os.path.getsize(self.filename)*8

    def getFilename(self, fullName):
        """Return the name of the file.
        e.g.: foo1/foo2/file.txt ==> file.txt"""
        return fullName.split('/')[-1]

    def askOpenFile(self):
        """Ask the user for a file.
        When a file is choose, the attribute
        and the label are update."""
        self.filename = fd.askopenfilename()
        if self.filename:
            self.fileLabel.set(self.getFilename(self.filename))

    def create_widgets(self):
        """Create the frame starting layout."""
        self.fileLabel = tk.StringVar()
        self.fileLabel.set('No file')

        tk.Button(self, text='Choose a file...', command=self.askOpenFile).grid(column=0, row=0, padx=10, pady=30)
        tk.Label(self, textvariable=self.fileLabel).grid(column=1, row=0)

    def __init__(self,master=None,size=(100,100)):
        super().__init__(master,size)
        self.filename = None
        self.create_widgets()
        super().create_widgets()
